home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11906 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: news1.erols.com!newsmaster@erols.com
  2. From: Chris Cobb <ccobb@erols.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: C++ keyword
  5. Date: 17 Mar 1996 00:45:31 GMT
  6. Organization: CSEG, Inc.
  7. Message-ID: <4ifnbb$amc@news7.erols.com>
  8. References: <mwoods-1403961501550001@ou048057.otago.ac.nz>
  9. NNTP-Posting-Host: ccobb.erols.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 1.22KIT (Windows; U; 16bit)
  14.  
  15. mwoods@maths.otago.ac.nz (Matt B. Woods) wrote:
  16. >I am fairly new to C++ and I have just come across the keyword 'throw'. 
  17. >As I cannot find a reference to this keyword I assume I must be reading
  18. >the wrong books.  Can anyone tell me what 'throw' means?  Even better
  19. >could someone recommend a good complete reference to the C++ language?
  20. >
  21.  
  22. Throw is used to throw exceptions.  Borland C++ 4.52 implements 
  23. exceptions but many compilers do not yet implement them.  The new 
  24. Standard C++ Library will throw exceptions on error conditions so it will 
  25. be prudent to understand how they work.  An article in the Jan 96 issue 
  26. of C++ Reports begins by describing how difficult they are to use, so 
  27. this should be kept in mind.  However, a *very* simple framework would 
  28. be:
  29.  
  30. even_numbers_only(int i)
  31. {
  32.    if (i % 2)
  33.       cout << i << " is even!" << endl;
  34.    else
  35.    {
  36.       cerr << i << " is not even!" << endl;
  37.       throw i;
  38.    }
  39. }
  40.  
  41. my_function()
  42. {
  43.    try // try block: followed by one or more catch blocks
  44.    {
  45.       // call functions here that might throw exceptions
  46.       even_numbers_only(3);
  47.    }
  48.    catch(...) // catch all exceptions
  49.    {
  50.       // some function in my try block threw an exception
  51.       cerr << "Exception caught: some function in my try block "
  52.            << "threw an exception!" << endl;
  53.       cerr << "Error occured in my_function()." << endl;
  54.    }
  55. }
  56.  
  57. Throw and catching exceptions is not unlike using setjmp() and longjmp() 
  58. in C.  One important difference is that throwing an exception causes
  59. all objects on the call stack (including the try block) to be properly
  60. destruct-ed, which would not happen with longjmp.
  61.  
  62. Chris Cobb
  63.  
  64.  
  65.